#!/bin/bash
# ===== Log =====
# log.info xxx
# log.warn xxx
# log.info xxx
# log.debug xxx
# 带颜色的echo
log.warn() { echo -e "[\e[33mWARN\e[0m]:  \e[1m$*\e[0m"; }
log.error()  { echo -e "[\e[31mERROR\e[0m]: \e[1m$*\e[0m"; }
log.info() { echo -e "[\e[96mINFO\e[0m]:  \e[1m$*\e[0m"; }
log.debug()  { echo -e "[\e[32mDEBUG\e[0m]: \e[1m$*\e[0m"; }

function kmre-apk-installer() {
    # Detect user using the display
    local user=$(who | awk '{print $1}' | head -n 1)
    sudo -u "$user" kmre-apk-installer "$@"
}

# echo -e "\e[30m 黑色 \e[0m"
# echo -e "\e[31m 红色 \e[0m"
# echo -e "\e[32m 绿色 \e[0m"
# echo -e "\e[33m 黄色 \e[0m"
# echo -e "\e[34m 蓝色 \e[0m"
# echo -e "\e[35m 紫色 \e[0m"
# echo -e "\e[36m 青色 \e[0m"
# echo -e "\e[37m 白色 \e[0m"

############################################################################开始
if [ "$UID" != "0" ]; then
    log.error "Need to be run as root."
    exit 1
fi

# 检查参数个数
if [ "$#" -ne 2 ]; then
    log.info "Usage: $0 desktop-file/package-name <desktop-file>/<packagename>"
    exit 1
fi

####################################变量配置（用于后续支持多个包管理系统）
# 清除先前的变量值
unset ABSOLUTE_PATH PKGNAME_GUESS DPKG_LIST_FILE ACE_ENV_PATH

if [[ "$1" = "package-name" ]]; then
    apt purge "$2" -y
    ret=$?
    if [ "$ret" = "0" ]; then
        log.info "Operation succeeded."
        exit 0
    else
        log.error "Operation failed."
        exit $ret
    fi

elif [[ "$1" = "desktop-file" ]]; then
    ####################################验证输入有效性
    # 保存并验证绝对路径
    ABSOLUTE_PATH=$(realpath "$2")
    ABSOLUTE_PATH_NO_REALPATH="$2"

    log.debug "ABSOLUTE_PATH=$ABSOLUTE_PATH"
    log.debug "ABSOLUTE_PATH_NO_REALPATH=$ABSOLUTE_PATH_NO_REALPATH"
    
    # 验证是否为desktop文件
    if [ ! -e "$ABSOLUTE_PATH" ]; then
        log.error "$ABSOLUTE_PATH does not exist. May have already been uninstalled"
        exit 1
    fi
    
    if [[ ! "$ABSOLUTE_PATH" == *.desktop ]]; then
        log.error "The file is not a desktop file."
        exit 1
    fi

    #############################################检查是否是KMRE包
    DESKTOP_FILE="$ABSOLUTE_PATH"
    
    # 检查是否包含 X-GXDE-KMREAPP=true
    if grep -q "X-GXDE-KMREAPP=true" "$DESKTOP_FILE"; then
        # 定义最大等待时间和重试间隔
        MAX_WAIT_TIME=30
        RETRY_INTERVAL=5
        
        # 读取 X-GXDE-KMRE-PKGNAME 的值
        PKGNAME=$(grep -oP 'X-GXDE-KMRE-PKGNAME=\K.*' "$DESKTOP_FILE")

        if [ -z "$PKGNAME" ]; then
            log.error "Error: X-GXDE-KMRE-PKGNAME not found in $DESKTOP_FILE"
            exit 1
        fi

        # 执行卸载操作
        start_time=$(date +%s)
        while true; do
            # 执行卸载命令
            kmre-apk-installer uninstall "$PKGNAME"
            exit_code=$?

            # 检查返回值
            if [ $exit_code -eq 0 ]; then
                log.info "Uninstall successful: $PKGNAME"
                exit 0
            elif [ $exit_code -eq 114 ]; then
                # 计算已等待的时间
                current_time=$(date +%s)
                elapsed_time=$((current_time - start_time))

                # 检查是否超时
                if [ $elapsed_time -ge $MAX_WAIT_TIME ]; then
                    log.error "Error: Timeout while waiting to uninstall $PKGNAME"
                    exit 1
                fi

                # 等待一段时间后重试
                log.info "Waiting to retry uninstall..."
                sleep $RETRY_INTERVAL
            elif [ $exit_code -eq -1 ]; then
                log.error "Error: Uninstall failed for $PKGNAME"
                exit 1
            else
                log.error "Error: Unknown exit code $exit_code"
                exit 1
            fi
        done
    else
        log.info "Skipping: $DESKTOP_FILE does not contain X-GXDE-KMREAPP=true"
    fi

    ######## APM
    if grep -q "X-APM-APPID=" "$DESKTOP_FILE"; then
        # 读取 X-APM-APPID 的值
        PKGNAME=$(grep -oP 'X-APM-APPID=\K.*' "$DESKTOP_FILE")

        if [ -z "$PKGNAME" ]; then
            log.error "Error: X-APM-APPID= is empty in $DESKTOP_FILE"
            exit 1
        fi
        
        # 修复：正确引用变量
        if amber-pm-debug dpkg -l | grep -q "^ii  $PKGNAME "; then
            apm autopurge "$PKGNAME" -y
            exit_code=$?
            if [ $exit_code -eq 0 ]; then
                log.info "Uninstall successful: $PKGNAME in APM"
                exit 0
            else
                log.error "Error: Uninstall failed for $PKGNAME in APM"
                exit 1
            fi
        else
            apt autopurge "$PKGNAME" -y
            exit_code=$?
            if [ $exit_code -eq 0 ]; then
                log.info "Uninstall successful: $PKGNAME in APM"
                exit 0
            else
                log.error "Error: Uninstall failed for $PKGNAME in APM"
                exit 1
            fi
        fi
    else
        log.info "Skipping: $DESKTOP_FILE does not contain X-APM-APPID"
    fi

    #############################################转发请求去ACE不同的卸载器
    # 1. 检查已有的环境
    # 查找/opt/apps/目录下以amber-ce-开头的目录
    ACE_ENV_PATHS=$(find "/opt/apps" -maxdepth 1 -name "amber-ce-*")
    log.info "$ACE_ENV_PATHS"
    
    # 2. 合成路径并进行匹配
    for ACE_ENV_PATH in $ACE_ENV_PATHS; do
        # 提取关键词（amber-ce-后面的部分）
        KEYWORD=$(basename "$ACE_ENV_PATH" | sed 's/^amber-ce-//')
        # 合成路径
        COMBINED_PATH="/opt/apps/amber-ce-$KEYWORD/files/ace-env"
        # 3. 逐条验证$ABSOLUTE_PATH变量是否以合成路径开头
        if [[ "${ABSOLUTE_PATH}" == "$COMBINED_PATH"* ]]; then
            # 如果匹配，执行uninstall-helper命令
            /opt/apps/amber-ce-"$KEYWORD"/files/bin/ace-uninstall-helper "${ABSOLUTE_PATH}"
            exit $?
        fi
    done

    ################################## Deb卸载
    # 首先尝试从desktop文件名猜测包名
    PKGNAME_GUESS=$(basename "$ABSOLUTE_PATH" .desktop)
    
    # 检查dpkg列表文件
    DPKG_INFO_PATH="/var/lib/dpkg/info"
    if [ -f "$DPKG_INFO_PATH/$PKGNAME_GUESS.list" ]; then
        DPKG_LIST_FILE="$DPKG_INFO_PATH/$PKGNAME_GUESS.list"
    elif ls "$DPKG_INFO_PATH/${PKGNAME_GUESS}:"*.list 1> /dev/null 2>&1; then
        DPKG_LIST_FILE=$(ls "$DPKG_INFO_PATH/${PKGNAME_GUESS}:"*.list | head -n 1)
    else
        log.warn "No dpkg list file found for $PKGNAME_GUESS.desktop, try to scan to search for the package"
    fi

    # 验证文件并执行操作
    if [ -f "$DPKG_LIST_FILE" ]; then
        if grep -q "$ABSOLUTE_PATH" "$DPKG_LIST_FILE"; then
            apt purge "$PKGNAME_GUESS" -y
            ret=$?
            if [ "$ret" = "0" ]; then
                log.info "Operation succeeded."
                exit 0
            else
                log.error "Operation failed."
                exit $ret
            fi
        else
            log.error "Path not found in the dpkg list file, try to scan to search for the package"
        fi
    fi

    # 遍历所有list文件 As fallback
    for file in "$DPKG_INFO_PATH"/*.list; do
        if grep -q "$ABSOLUTE_PATH" "$file"; then
            PKGNAME_GUESS=$(basename "$file" .list | cut -d':' -f1)
            log.info "Get pkgname $PKGNAME_GUESS, uninstalling..."
            apt purge "$PKGNAME_GUESS" -y
            ret=$?
            if [ "$ret" = "0" ]; then
                log.info "Operation succeeded."
                exit 0
            else
                log.error "Operation failed."
                exit $ret
            fi
        fi
    done

    #############################################最后是pkcon卸载
    log.info "It seems like a 3-rd party package manager app. Try pkcon uninstall..."
    # 截取并保存包名
    PKGNAME_GUESS=$(basename "$ABSOLUTE_PATH" .desktop)
    pkcon remove "$PKGNAME_GUESS" -y
    ret=$?
    if [ "$ret" = "0" ]; then
        log.info "Operation succeeded."
        exit 0
    else
        log.error "Operation failed"
        exit $ret
    fi

    ########如果所有的卸载都没有匹配，则报错退出
    log.error "Error: No matching package found."
    exit 1

else
    log.error "Error: unknown option."
    exit 1
fi